<script setup>
import { inject, ref, onMounted, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useCssVar, useDark } from '@vueuse/core'
import userApi from '@/apis/user'
import { useConfigStore } from '@/stores/config'

const user = inject('user')
const isSmallPage = inject('isSmallPage')
const configStore = useConfigStore()

const day = ref(new Date())
const loaded = ref(false)
const items = ref([])
const lastItem = ref({})

const isDark = useDark()

const rewardScore = computed(() => {
  return configStore.get('user.invite_enabled') === true ? configStore.get('user.invite_reward') : 0
})

const getData = async (date) => {
  const { data } = await userApi.signIn.monthData(date.getFullYear(), date.getMonth() + 1)
  items.value = data
  loaded.value = true
}

const getCurrentMonthData = async () => {
  await getData(new Date())
  if (items.value.length > 0) {
    const item = items.value[items.value.length - 1]
    //判断item.day(格式yyyy-mm-dd)是不是昨天或者今天的数据，且连续签到不到7天（7天表示结束)
    if ((isYesterday(item.day) && item.step < 7) || (isToday(item.day) && item.step <= 7)) {
      lastItem.value = item
    }
  }
}

const getToday = () => {
  const now = new Date()
  const year = now.getFullYear()
  //月和日个位数时前吗补0
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  //格式 yyyy-mm-dd
  return `${year}-${month}-${day}`
}
const today = getToday()

const isToday = (day) => {
  const date = new Date(day)
  const now = new Date()
  return date.toDateString() === now.toDateString()
}

const isYesterday = (day) => {
  const itemDate = new Date(day)
  const today = new Date()
  return itemDate.toDateString() === new Date(today.setDate(today.getDate() - 1)).toDateString()
}

const isSigned = (day) => {
  return typeof getSign(day) !== 'undefined'
}

const getSign = (day) => {
  return items.value.find((item) => item.day === day)
}

const sign = async () => {
  await userApi.signIn.tick()
  ElMessage.success('签到成功')
  await getCurrentMonthData()
}

watch(day, (newDate, old) => {
  //判断val和old是不是同一个年份和月份
  if (newDate.getFullYear() !== old.getFullYear() || newDate.getMonth() !== old.getMonth()) {
    getData(newDate)
  }
})

watch(
  isDark,
  () => {
    nextTick(() => {
      if (isSmallPage.value) {
        //设置背景色
        const bgColor = useCssVar('--el-fill-color-lighter')
        document.body.style.backgroundColor = bgColor.value
      }
    })
  },
  {
    immediate: true,
  }
)

onMounted(() => getCurrentMonthData())
</script>

<template>
  <div class="pc-page">
    <div class="mt-3 mx-3 sm:mx-5 space-y-4">
      <div class="text-xl font-bold">签到奖励</div>
      <div class="text-sm text-[--el-text-color-secondary]">
        签到即可获得积分奖励，连续签到可获得更多积分。
      </div>
      <div class="w-full">
        <el-calendar v-model="day">
          <template #date-cell="{ data }">
            <p :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split('-').slice(2).join('-') }}
            </p>
            <p>
              <template v-if="isSigned(data.day)">
                <el-tag size="small" type="success">
                  <FontAwesomeIcon icon="coins" class="text-[--el-color-warning]" />
                  +{{ getSign(data.day).score }}
                </el-tag>
              </template>
              <!-- 加 loaded条件 时为了方式 v-if 闪现 -->
              <template v-else-if="isToday(data.day) && loaded">
                <el-button size="small" type="primary" @click="sign" round>
                  <FontAwesomeIcon icon="coins" />
                  <span class="pl-0.5">签到</span>
                </el-button>
              </template>
            </p>
          </template>
        </el-calendar>
      </div>
    </div>
  </div>
  <div class="small-page">
    <div class="flex justify-between pt-4 pb-28 px-3 bg-[--el-color-warning-light-5]">
      <div class="absolute bottom-18 right-6">
        <FontAwesomeIcon icon="coins" class="text-[--el-color-warning-light-7]" size="5x" />
      </div>
      <div class="flex flex-col mt-1 ml-1">
        <div class="text-base text-[--el-color-warning]">当前积分</div>
        <div class="text-3xl text-[--el-fill-color-lighter]">{{ user.score }}</div>
      </div>
    </div>
    <div class="relative -top-20 px-4">
      <div
        class="rounded-lg shadow shadow-[--el-color-info-light-8] text-[--el-text-color-regular] bg-[--el-color-warning-light-5]"
      >
        <div class="rounded-lg py-3 px-3 bg-[--el-bg-color] space-y-2">
          <!-- 头部 -->
          <div class="flex justify-between items-center">
            <div class="text-sm ml-1">已连续签到 {{ lastItem ? lastItem.step : 0 }} 天</div>
            <el-button v-if="isSigned(today)" type="warning" size="small" round disabled>
              <FontAwesomeIcon icon="check" />
              <span class="pl-1">今日已签到</span>
            </el-button>
            <el-button type="warning" size="small" @click="sign" round v-else>
              <FontAwesomeIcon icon="coins" />
              <span class="pl-1">签到</span>
            </el-button>
          </div>
          <!-- 签到日历 -->
          <div class="flex justify-between">
            <div v-for="i in 7" :key="i" class="space-y-1 w-[11%] text-center">
              <div
                :class="{
                  'day-item': true,
                  signed: lastItem && i <= lastItem.step,
                }"
              >
                <div class="mt-1">
                  <FontAwesomeIcon icon="check" size="xs" v-if="lastItem && i <= lastItem.step" />
                  <FontAwesomeIcon icon="coins" size="xs" v-else />
                </div>
                <div><span class="text-xs">+5</span></div>
              </div>
              <span class="text-sm">{{ i }}天</span>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-4 space-y-2">
        <div class="text-base">其他奖励</div>
        <div
          class="flex flex-col space-y-1 bg-[--el-bg-color] px-3 rounded-lg shadow-sm shadow-[--el-color-info-light-8]"
        >
          <div class="task-item" v-if="rewardScore > 0">
            <div class="flex flex-col space-y-1">
              <div>邀请好友</div>
              <span class="text-sm text-[--el-text-color-regular]">
                邀请一位好友注册奖励 {{ rewardScore }} 积分
              </span>
            </div>
            <RouterLink :to="{ name: 'userInvite' }">
              <el-button type="warning" size="small" round plain>去邀请</el-button>
            </RouterLink>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.el-calendar__header,
.el-calendar__body {
  padding: 0 !important;
}

.pc-page {
  @apply hidden sm:block text-[--el-text-color-primary];
}

.small-page {
  @apply sm:hidden; /* bg-[--el-fill-color-light] */
}

.day-item {
  @apply flex flex-col rounded-t-full rounded-b-full py-2 text-center items-center leading-4 bg-[--el-color-warning-light-9] text-[--el-color-warning] my-2;
}

.day-item.signed {
  @apply bg-[--el-color-warning-light-3] text-gray-100;
}

.task-item {
  @apply flex justify-between items-center border-b border-b-[--el-border-color] last:border-b-0 py-3;
}
</style>
